#!/usr/bin/env bash

export PATH="${PATH}:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin"

ME="$(basename ${0})"

# -----------------------------------------------------------------------------
# show what is happening

echo >&2 "${ME}: '${STATE}' event for '${DESTNODE}' (${DESTID}) at '${DESTSI}' (ip '${DESTIP}', port '${DESTPORT}'), running on '${NODENAME}' (${NODEID}), interface '${IFNAME}' (type '${IFTYPE}', subtype '${IFSUBTYPE}', mac '${MAC}', mtu '${MTU}', ifupdata '${IFUPDATA}'), config '${CONFBASE}', nodes ${NODES}"


[ -f ${CONFBASE}/status/${DESTNODE} ] && \
	. ${CONFBASE}/status/${DESTNODE}

cat >${CONFBASE}/status/${DESTNODE} <<EOF
nodeid="${DESTID}"
name="${DESTNODE}"
status="${STATE}"
ip="${ip}"
si="${DESTSI}"
pip="${pip}"
pipport="${pipport}"
rip="${DESTIP}"
ripport="${DESTPORT}"
mac="${mac}"
ifupdata="${ifupdata}"
timestamp="$(date +%s)"
EOF

# -----------------------------------------------------------------------------
# set the counters

EVENTS=0
NODES_UP=1
NODES_DOWN=$((NODES - 1))

[ -f ${CONFBASE}/status/status ] && \
	source ${CONFBASE}/status/status

case "${STATE}" in
	up)
		NODES_UP=$((NODES_UP + 1))
		NODES_DOWN=$((NODES_DOWN - 1))
		;;

	down)
		NODES_UP=$((NODES_UP - 1))
		NODES_DOWN=$((NODES_DOWN + 1))
		;;
esac

[ ${NODES_UP}   -lt 1        ] && NODES_UP=1
[ ${NODES_UP}   -gt ${NODES} ] && NODES_UP=${NODES}
[ ${NODES_DOWN} -lt 0        ] && NODES_DOWN=0
[ ${NODES_DOWN} -gt ${NODES} ] && NODES_DOWN=${NODES}

[ $((NODES_UP + NODES_DOWN)) -ne ${NODES} ] && \
	NODES_UP = $((NODES - NODES_DOWN))

cat >${CONFBASE}/status/status <<EOF
MYNODENAME=${NODENAME}
MYNODEID=${NODEID}
EVENTS=$((EVENTS + 1))
NODES_ALL=${NODES}
NODES_UP=${NODES_UP}
NODES_DOWN=${NODES_DOWN}
NODES_DISABLED=${NODES_DISABLED}
timestamp="$(date +%s)"
EOF

# -----------------------------------------------------------------------------
# execute any local action

if [ -x ${CONFBASE}/${ME}.local ]
	then
	${CONFBASE}/${ME}.local "${@}"
	exit $?
fi

exit 0
